/*
 * Copyright (C) 2015 Brent Marriott
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hookedonplay.decoviewlib.util;

import ohos.agp.window.service.Display;
import ohos.agp.window.service.DisplayAttributes;
import ohos.agp.window.service.DisplayManager;
import ohos.app.Context;
import org.jetbrains.annotations.NonNls;

import java.util.Optional;

@SuppressWarnings("unused")
public class GenericFunctions {
    private static boolean mInitialized;
    private static float mScaledDensity = 3.0f;

    public static void initialize(@NonNls Context context) {
        mInitialized = true;
        Optional<Display> defaultDisplay = DisplayManager.getInstance().getDefaultDisplay(context.getApplicationContext());
        Display display = defaultDisplay.get();
        DisplayAttributes attributes = display.getAttributes();
        mScaledDensity = attributes.scalDensity;
    }

    public static float pixelsToSp(final float px) {
        verifyInitialized();
        return px / mScaledDensity;
    }

    public static int spToPixels(final float sp) {
        verifyInitialized();
        return (int) (sp * mScaledDensity);
    }

    public static void verifyInitialized() throws IllegalStateException {
        if (!mInitialized) {
            throw new IllegalStateException("Missing call to GenericFunctions::initialize()");
        }
    }
}